#pragma once

#include <unordered_map>
#include <functional>
#include <iostream>
#include <ctime>
#include <sys/types.h>
#include <unistd.h>

using task_t = std::function<void()>;
static int task_number = 0;

void DownLoad()
{
    std::cout << "我是下载任务! pid: " << getpid() << std::endl;
}

void Log()
{
    std::cout << "我是日志任务! pid: " << getpid() << std::endl;
}

void Sql()
{
    std::cout << "我是数据库同步任务! pid: " << getpid() << std::endl;
}

class TaskManager
{
public:
    TaskManager()
    {
        srand(time(nullptr));
        InsertTask(DownLoad);
        InsertTask(Log);
        InsertTask(Sql);
    }
    void InsertTask(task_t t)
    {
        _tasks[task_number++] = t;
    }
    int SelectTask()
    {
        return rand() % task_number; // 随机选择一个任务
    }
    void ExecuteTask(int task_code)
    {
        if (_tasks.find(task_code) == _tasks.end())
            return;          // 找不到该任务
        _tasks[task_code](); // 找到后就执行
    }
    ~TaskManager()
    {
    }

private:
    std::unordered_map<int, task_t> _tasks; // 任务码：任务内容
};

TaskManager tm;

void Work()
{
    while (true)
    {
        int cmd = 0;
        int n = ::read(0, &cmd, sizeof(cmd));
        if (n == sizeof(cmd))
        {
            tm.ExecuteTask(cmd);
        }
        else if (n == 0)
        {
            break;
        }
        else
        {
        }
    }
}